<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="路段名称" prop="roadName">
        <el-select v-model="queryParams.roadName" placeholder="请选择路段名称" clearable filterable>
          <el-option
            v-for="dict in dict.type.sys_road"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="起点/迄点" prop="nodeName">
        <el-input
          v-model="queryParams.nodeName"
          placeholder="请输入起点/迄点"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
	    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['functiontest:RoadSectionDistanceTest:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['functiontest:RoadSectionDistanceTest:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleImport"
          v-hasPermi="['functiontest:RoadSectionDistanceTest:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleFieldAudit"
          v-hasPermi="['functiontest:RoadSectionDistanceTest:fieldAudit']"
        >实测单位审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleOwnerAudit"
          v-hasPermi="['functiontest:RoadSectionDistanceTest:ownerAudit']"
        >业主审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleCenterAudit"
          v-hasPermi="['functiontest:RoadSectionDistanceTest:centerAudit']"
        >中心审核</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="RoadSectionDistanceTestList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="父节点ID" prop="parentId" />
      <el-table-column label="路段名称" align="center" prop="roadName">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_road" :value="scope.row.roadName"/>
        </template>
      </el-table-column>
      <el-table-column label="起点/迄点" align="center" prop="nodeName" />
      <el-table-column label="左幅长度" align="center" prop="leftLength">
        <template slot-scope="scope">
          <span v-if="scope.row.leftLength">{{ scope.row.leftLength }}米</span>
        </template>
      </el-table-column>
      <el-table-column label="右幅长度" align="center" prop="rightLength">
        <template slot-scope="scope">
          <span v-if="scope.row.rightLength">{{ scope.row.rightLength }}米</span>
        </template>
      </el-table-column>
      <el-table-column label="平均长度" align="center" prop="avgLength">
        <template slot-scope="scope">
          <span v-if="scope.row.avgLength">{{ scope.row.avgLength }}米</span>
        </template>
      </el-table-column>
      <el-table-column label="备注信息" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['functiontest:RoadSectionDistanceTest:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['functiontest:RoadSectionDistanceTest:add']"
            v-if="scope.row.parentId === 0"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['functiontest:RoadSectionDistanceTest:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改主线站点间里程实测数据测试对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父节点ID" prop="parentId" v-if="addLevel === 3">
          <treeselect v-model="form.parentId" :options="RoadSectionDistanceTestOptions" :normalizer="normalizer" placeholder="请选择父节点ID" />
        </el-form-item>
        <el-form-item label="路段名称" prop="roadName" v-if="addLevel === 1">
          <el-select v-model="form.roadName" placeholder="请选择路段名称" clearable filterable>
            <el-option
              v-for="dict in dict.type.sys_road"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="起点/迄点" prop="nodeName" v-if="addLevel === 2 || addLevel === 3">
          <el-input v-model="form.nodeName" placeholder="请输入起点/迄点" />
        </el-form-item>
        <el-form-item label="左幅长度(米)" prop="leftLength" v-if="addLevel === 2 || addLevel === 3">
          <el-input v-model="form.leftLength" placeholder="请输入左幅长度" @input="calculateAvgLength" />
        </el-form-item>
        <el-form-item label="右幅长度(米)" prop="rightLength" v-if="addLevel === 2 || addLevel === 3">
          <el-input v-model="form.rightLength" placeholder="请输入右幅长度" @input="calculateAvgLength" />
        </el-form-item>
        <el-form-item label="平均长度(米)" prop="avgLength" v-if="addLevel === 2 || addLevel === 3">
          <el-input v-model="form.avgLength" placeholder="自动计算" :disabled="true" />
        </el-form-item>
        <el-form-item label="备注信息" prop="remark" v-if="addLevel === 2 || addLevel === 3">
          <el-input v-model="form.remark" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRoadSectionDistanceTest, getRoadSectionDistanceTest, delRoadSectionDistanceTest, addRoadSectionDistanceTest, updateRoadSectionDistanceTest, exportRoadSectionDistanceTest } from "@/api/functiontest/RoadSectionDistanceTest"
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import { getUserProfile } from "@/api/system/user"


export default {
  name: "RoadSectionDistanceTest",
  dicts: ['sys_road'],
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 主线站点间里程实测数据测试表格数据
      RoadSectionDistanceTestList: [],
      // 主线站点间里程实测数据测试树选项
      RoadSectionDistanceTestOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        roadName: null,
        nodeName: null,
        deptId: null,
        roleId: null,
      },
      // 导出遮罩层
      exportLoading: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      deptId: null,
      roleId: null,
      // 新增层级标识：1-第一层，2-第二层，3-第三层
      addLevel: 1,
    }
  },
  created() {
    this.getUser().then(() => {
      this.getList();
    });
  },
  methods: {
    getUser() {
      return getUserProfile().then(response => {
        if(response.data.roles[0].roleId != 1) {
          this.deptId = response.data.dept.deptId
        }else{
          this.deptId = null
        }
        this.roleId = response.data.roles[0].roleId
      })
    },
    /** 查询主线站点间里程实测数据测试列表 */
    getList() {
      this.queryParams.deptId = this.deptId
      this.queryParams.roleId = this.roleId
      this.loading = true
      listRoadSectionDistanceTest(this.queryParams).then(response => {
        this.RoadSectionDistanceTestList = this.handleTree(response.data, "id", "parentId")
        // 计算一级节点的平均值
        this.calculateFirstLevelAvg()
        this.loading = false
      })
    },
    /** 转换主线站点间里程实测数据测试数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.roadName,
        children: node.children
      }
    },
	/** 查询主线站点间里程实测数据测试下拉树结构 */
    getTreeselect() {
      listRoadSectionDistanceTest().then(response => {
        this.RoadSectionDistanceTestOptions = []
        const data = { id: 0, roadName: '顶级节点', children: [] }
        data.children = this.handleTree(response.data, "id", "parentId")
        this.RoadSectionDistanceTestOptions.push(data)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: null,
        roadName: null,
        nodeName: null,
        leftLength: null,
        rightLength: null,
        avgLength: null,
        remark: null
      }
      this.addLevel = 1 // 重置新增层级标识
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.getTreeselect()
      if (row != null && row.id) {
        this.form.parentId = row.id
        // 判断新增层级：如果父节点parentId为0，则新增第二层；否则为其他层级
        if (row.parentId === 0) {
          this.addLevel = 2 // 新增第二层
        } else {
          this.addLevel = 3 // 新增第三层
        }
      } else {
        this.form.parentId = 0
        this.addLevel = 1 // 新增第一层
      }
      this.open = true
      this.title = "添加主线站点间里程实测数据测试"
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getTreeselect()
      if (row != null) {
        this.form.parentId = row.parentId
        // 根据节点层级设置addLevel变量，控制修改对话框中的字段显示
        if (row.parentId === 0) {
          this.addLevel = 1 // 修改第一层
          getRoadSectionDistanceTest(row.id).then(response => {
            this.form = response.data
            this.open = true
            this.title = "修改主线站点间里程实测数据测试"
          })
        } else {
          // 获取完整的树结构数据，判断父节点的父节点
          listRoadSectionDistanceTest().then(response => {
            const fullTreeData = this.handleTree(response.data, "id", "parentId");
            
            // 查找节点的函数
            const findNode = (nodes, targetId) => {
              for (let node of nodes) {
                if (node.id === targetId) {
                  return node;
                }
                if (node.children && node.children.length > 0) {
                  const found = findNode(node.children, targetId);
                  if (found) {
                    return found;
                  }
                }
              }
              return null;
            };
            
            // 查找当前节点的父节点
            const parentNode = findNode(fullTreeData, row.parentId);
            
            // 判断层级
            if (parentNode && parentNode.parentId === 0) {
              this.addLevel = 2; // 修改第二层
            } else {
              this.addLevel = 3; // 修改第三层
            }
            
            getRoadSectionDistanceTest(row.id).then(response => {
              this.form = response.data
              this.open = true
              this.title = "修改主线站点间里程实测数据测试"
            })
          });
        }
      } else {
        getRoadSectionDistanceTest(row.id).then(response => {
          this.form = response.data
          this.open = true
          this.title = "修改主线站点间里程实测数据测试"
        })
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRoadSectionDistanceTest(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
              // 修改后计算平均值
              this.calculateAvgLengthAfterUpdate();
            })
          } else {
            addRoadSectionDistanceTest(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
              // 新增后计算平均值
              this.calculateAvgLengthAfterAdd(response.data.id);
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const parentId = row.parentId; // 保存父节点ID用于计算平均值
      this.$modal.confirm('是否确认删除主线站点间里程实测数据测试编号为"' + row.id + '"的数据项？').then(function() {
        return delRoadSectionDistanceTest(row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
        // 删除后计算平均值
        if (parentId !== 0 && parentId !== null) {
          this.calculateAvgLengthAfterDelete(row.id, parentId);
        }
      }).catch(() => {})
    },
    /** 计算平均长度 */
    calculateAvgLength() {
      const left = parseFloat(this.form.leftLength) || 0;
      const right = parseFloat(this.form.rightLength) || 0;
      // 如果左右幅长度都存在，则计算平均长度，保留四位小数
      if (left > 0 && right > 0) {
        this.form.avgLength = ((left + right) / 2).toFixed(4);
      } else if (left > 0 || right > 0) {
        // 如果只有一边有数据，则直接使用该数据作为平均长度，保留四位小数
        this.form.avgLength = (left + right).toFixed(4);
      } else {
        // 如果都没有数据，则清空平均长度
        this.form.avgLength = '';
      }
    },
    /** 修改后计算平均长度 */
    calculateAvgLengthAfterUpdate() {
      // 只有当当前节点有父节点时才需要计算平均长度
      if (this.form.parentId !== 0 && this.form.parentId !== null) {
        // 获取完整的树结构数据
        listRoadSectionDistanceTest().then(response => {
          const fullTreeData = this.handleTree(response.data, "id", "parentId");
          
          // 查找节点的函数
          const findNode = (nodes, targetId) => {
            for (let node of nodes) {
              if (node.id === targetId) {
                return node;
              }
              if (node.children && node.children.length > 0) {
                const found = findNode(node.children, targetId);
                if (found) {
                  return found;
                }
              }
            }
            return null;
          };
          
          // 查找当前表单节点的父节点
          const parentNode = findNode(fullTreeData, this.form.parentId);
          
          // 确保父节点存在
          if (parentNode) {
            // 查找父节点的父节点
            const grandParentNode = findNode(fullTreeData, parentNode.parentId);
            
            // 确保父节点的父节点存在
            if (grandParentNode) {
              // 如果父节点的父节点存在且parentId为0，则当前节点是三级节点
              // 父节点是二级节点，父节点的父节点是一级节点
              if (grandParentNode.parentId === 0) {
                // 当前正在编辑的是三级节点，需要计算其兄弟节点（同为三级节点）的平均长度
                // 并更新其父节点（二级节点）的平均长度
                
                // 获取所有兄弟节点（包括当前节点）
                const siblingNodes = parentNode.children || [];
                
                // 计算左幅长度和右幅长度的平均值
                let leftLengthSum = 0;
                let rightLengthSum = 0;
                let validNodeCount = 0;
                
                siblingNodes.forEach(node => {
                  const leftLength = parseFloat(node.leftLength);
                  const rightLength = parseFloat(node.rightLength);
                  if (!isNaN(leftLength) && !isNaN(rightLength)) {
                    leftLengthSum += leftLength;
                    rightLengthSum += rightLength;
                    validNodeCount++;
                  }
                });
                
                // 计算平均长度
                let avgLeftLength = 0;
                let avgRightLength = 0;
                let avgLength = 0;
                
                if (validNodeCount > 0) {
                  avgLeftLength = leftLengthSum / validNodeCount;
                  avgRightLength = rightLengthSum / validNodeCount;
                  avgLength = (avgLeftLength + avgRightLength) / 2;
                }
                
                // 更新父节点（二级节点）的长度值，保留四位小数
                parentNode.leftLength = parseFloat(avgLeftLength.toFixed(4));
                parentNode.rightLength = parseFloat(avgRightLength.toFixed(4));
                parentNode.avgLength = parseFloat(avgLength.toFixed(4));
                
                // 更新父节点的长度值到数据库
                const parentForm = {
                  id: parentNode.id,
                  leftLength: parentNode.leftLength,
                  rightLength: parentNode.rightLength,
                  avgLength: parentNode.avgLength
                };
                
                // 调用更新接口更新父节点
                updateRoadSectionDistanceTest(parentForm).then(response => {
                  // console.log("二级节点平均长度更新成功");
                  // 更新一级节点的平均值
                  this.calculateFirstLevelAvg();
                  // 更新成功后刷新列表
                  this.getList();
                }).catch(error => {
                  console.error("二级节点平均长度更新失败:", error);
                  this.$modal.msgError("二级节点平均长度更新失败");
                  // 即使更新失败也刷新列表
                  this.getList();
                });
              } else {
                // 如果不是三级节点，直接刷新列表
                this.getList();
              }
            } else {
              // 如果没有祖父节点，直接刷新列表
              this.getList();
            }
          } else {
            // 如果没有找到父节点，直接刷新列表
            this.getList();
          }
        }).catch(error => {
          console.error("获取完整树结构数据失败:", error);
          this.$modal.msgError("获取数据失败，无法计算平均长度");
          // 即使获取数据失败也刷新列表
          this.getList();
        });
      } else {
        // 如果没有父节点，直接刷新列表
        this.getList();
      }
    },
    
    /** 新增节点后计算平均长度 */
    calculateAvgLengthAfterAdd(newNodeId) {
      // 获取完整的树结构数据，包括刚刚新增的节点
      listRoadSectionDistanceTest().then(response => {
        const fullTreeData = this.handleTree(response.data, "id", "parentId");
        
        // 查找节点的函数
        const findNode = (nodes, targetId) => {
          for (let node of nodes) {
            if (node.id === targetId) {
              return node;
            }
            if (node.children && node.children.length > 0) {
              const found = findNode(node.children, targetId);
              if (found) {
                return found;
              }
            }
          }
          return null;
        };
        
        // 查找新增的节点
        const newNode = findNode(fullTreeData, newNodeId);
        
        // 确保新增节点存在
        if (newNode) {
          // 查找新增节点的父节点
          const parentNode = findNode(fullTreeData, newNode.parentId);
          
          // 确保父节点存在
          if (parentNode) {
            // 查找父节点的父节点
            const grandParentNode = findNode(fullTreeData, parentNode.parentId);
            
            // 确保父节点的父节点存在
            if (grandParentNode) {
              // 如果父节点的父节点存在且parentId为0，则当前节点是三级节点
              // 父节点是二级节点，父节点的父节点是一级节点
              if (grandParentNode.parentId === 0) {
                // 当前新增的是三级节点，需要计算其兄弟节点（同为三级节点）的平均长度
                // 并更新其父节点（二级节点）的平均长度
                
                // 获取所有兄弟节点（包括当前新增节点）
                const siblingNodes = parentNode.children || [];
                
                // 计算左幅长度和右幅长度的平均值
                let leftLengthSum = 0;
                let rightLengthSum = 0;
                let validNodeCount = 0;
                
                siblingNodes.forEach(node => {
                  const leftLength = parseFloat(node.leftLength);
                  const rightLength = parseFloat(node.rightLength);
                  if (!isNaN(leftLength) && !isNaN(rightLength)) {
                    leftLengthSum += leftLength;
                    rightLengthSum += rightLength;
                    validNodeCount++;
                  }
                });
                
                // 计算平均长度
                let avgLeftLength = 0;
                let avgRightLength = 0;
                let avgLength = 0;
                
                if (validNodeCount > 0) {
                  avgLeftLength = leftLengthSum / validNodeCount;
                  avgRightLength = rightLengthSum / validNodeCount;
                  avgLength = (avgLeftLength + avgRightLength) / 2;
                }
                
                // 更新父节点（二级节点）的长度值
                parentNode.leftLength = parseFloat(avgLeftLength.toFixed(4));
                parentNode.rightLength = parseFloat(avgRightLength.toFixed(4));
                parentNode.avgLength = parseFloat(avgLength.toFixed(4));
                
                // 更新父节点的长度值到数据库
                const parentForm = {
                  id: parentNode.id,
                  leftLength: parentNode.leftLength,
                  rightLength: parentNode.rightLength,
                  avgLength: parentNode.avgLength
                };
                
                // 调用更新接口更新父节点
                updateRoadSectionDistanceTest(parentForm).then(response => {
                  // console.log("二级节点平均长度更新成功");
                  // 更新一级节点的平均值
                  this.calculateFirstLevelAvg();
                  // 更新成功后刷新列表
                  this.getList();
                }).catch(error => {
                  console.error("二级节点平均长度更新失败:", error);
                  this.$modal.msgError("二级节点平均长度更新失败");
                  // 即使更新失败也刷新列表
                  this.getList();
                });
              } else {
                // 如果不是三级节点，直接刷新列表
                this.getList();
              }
            } else {
              // 如果没有祖父节点，直接刷新列表
              this.getList();
            }
          } else {
            // 如果没有找到父节点，直接刷新列表
            this.getList();
          }
        } else {
          // 如果没有找到新增节点，直接刷新列表
          this.getList();
        }
      }).catch(error => {
        console.error("获取完整树结构数据失败:", error);
        this.$modal.msgError("获取数据失败，无法计算平均长度");
        // 即使获取数据失败也刷新列表
        this.getList();
      }).finally(() => {
        // 确保无论如何都会刷新列表
        this.getList();
      });
    },
    
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有主线站点间里程实测数据测试项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return exportRoadSectionDistanceTest(queryParams);
      }).then(response => {
        this.$download.saveAs(response, '主线站点里程实测数据测试.xlsx');
      }).catch(function() {});
    },
    /** 删除后计算平均长度 */
    calculateAvgLengthAfterDelete(deletedNodeId, parentNodeId) {
      // 获取完整的树结构数据，不包括刚刚删除的节点
      listRoadSectionDistanceTest().then(response => {
        const fullTreeData = this.handleTree(response.data, "id", "parentId");
        
        // 查找节点的函数
        const findNode = (nodes, targetId) => {
          for (let node of nodes) {
            if (node.id === targetId) {
              return node;
            }
            if (node.children && node.children.length > 0) {
              const found = findNode(node.children, targetId);
              if (found) {
                return found;
              }
            }
          }
          return null;
        };
        
        // 查找删除节点的父节点
        const parentNode = findNode(fullTreeData, parentNodeId);
        
        // 确保父节点存在
        if (parentNode) {
          // 查找父节点的父节点
          const grandParentNode = findNode(fullTreeData, parentNode.parentId);
          
          // 确保父节点的父节点存在
          if (grandParentNode) {
            // 如果父节点的父节点存在且parentId为0，则当前节点是三级节点
            // 父节点是二级节点，父节点的父节点是一级节点
            if (grandParentNode.parentId === 0) {
              // 当前删除的是三级节点，需要计算其兄弟节点（同为三级节点）的平均长度
              // 并更新其父节点（二级节点）的平均长度
              
              // 获取所有兄弟节点（不包括当前删除节点）
              const siblingNodes = parentNode.children || [];
              
              // 计算左幅长度和右幅长度的平均值
              let leftLengthSum = 0;
              let rightLengthSum = 0;
              let validNodeCount = 0;
              
              siblingNodes.forEach(node => {
                const leftLength = parseFloat(node.leftLength);
                const rightLength = parseFloat(node.rightLength);
                if (!isNaN(leftLength) && !isNaN(rightLength)) {
                  leftLengthSum += leftLength;
                  rightLengthSum += rightLength;
                  validNodeCount++;
                }
              });
              
              // 计算平均长度
              let avgLeftLength = 0;
              let avgRightLength = 0;
              let avgLength = 0;
              
              if (validNodeCount > 0) {
                avgLeftLength = leftLengthSum / validNodeCount;
                avgRightLength = rightLengthSum / validNodeCount;
                avgLength = (avgLeftLength + avgRightLength) / 2;
              }
              
              // 更新父节点（二级节点）的长度值，保留四位小数
              parentNode.leftLength = parseFloat(avgLeftLength.toFixed(4));
              parentNode.rightLength = parseFloat(avgRightLength.toFixed(4));
              parentNode.avgLength = parseFloat(avgLength.toFixed(4));
              
              // 更新父节点的长度值到数据库
              const parentForm = {
                id: parentNode.id,
                leftLength: parentNode.leftLength,
                rightLength: parentNode.rightLength,
                avgLength: parentNode.avgLength
              };
              
              // 调用更新接口更新父节点
              updateRoadSectionDistanceTest(parentForm).then(response => {
                // console.log("二级节点平均长度更新成功");
                // 更新一级节点的平均值
                this.calculateFirstLevelAvg();
                // 更新成功后刷新列表
                this.getList();
              }).catch(error => {
                console.error("二级节点平均长度更新失败:", error);
                this.$modal.msgError("二级节点平均长度更新失败");
                // 即使更新失败也刷新列表
                this.getList();
              });
            } else {
              // 如果不是三级节点，直接刷新列表
              this.getList();
            }
          } else {
            // 如果没有祖父节点，直接刷新列表
            this.getList();
          }
        } else {
          // 如果没有找到父节点，直接刷新列表
          this.getList();
        }
      }).catch(error => {
        console.error("获取完整树结构数据失败:", error);
        this.$modal.msgError("获取数据失败，无法计算平均长度");
        // 即使获取数据失败也刷新列表
        this.getList();
      }).finally(() => {
        // 确保无论如何都会刷新列表
        this.getList();
      });
    },
    
    /** 计算一级节点的平均值（根据二级节点的数据） */
    calculateFirstLevelAvg() {
      // 遍历所有一级节点，并根据其二级子节点计算平均值
      this.RoadSectionDistanceTestList.forEach(firstLevelNode => {
        // 一级节点的parentId为0
        if (firstLevelNode.parentId === 0 && firstLevelNode.children && firstLevelNode.children.length > 0) {
          // 计算所有二级节点的平均值
          let leftLengthSum = 0;
          let rightLengthSum = 0;
          let validNodeCount = 0;
          
          firstLevelNode.children.forEach(secondLevelNode => {
            const leftLength = parseFloat(secondLevelNode.leftLength);
            const rightLength = parseFloat(secondLevelNode.rightLength);
            if (!isNaN(leftLength) && !isNaN(rightLength)) {
              leftLengthSum += leftLength;
              rightLengthSum += rightLength;
              validNodeCount++;
            }
          });
          
          // 计算平均长度，使用四位小数进行计算
          let avgLeftLength = 0;
          let avgRightLength = 0;
          let avgLength = 0;
          
          if (validNodeCount > 0) {
            avgLeftLength = leftLengthSum / validNodeCount;
            avgRightLength = rightLengthSum / validNodeCount;
            avgLength = (avgLeftLength + avgRightLength) / 2;
          }
          
          // 更新一级节点的长度值，显示时保留两位小数
          firstLevelNode.leftLength = parseFloat(avgLeftLength.toFixed(2));
          firstLevelNode.rightLength = parseFloat(avgRightLength.toFixed(2));
          firstLevelNode.avgLength = parseFloat(avgLength.toFixed(2));
          
          // 将更新后的一级节点数据保存到数据库，使用四位小数
          const firstLevelForm = {
            id: firstLevelNode.id,
            leftLength: parseFloat(avgLeftLength.toFixed(2)),
            rightLength: parseFloat(avgRightLength.toFixed(2)),
            avgLength: parseFloat(avgLength.toFixed(2))
          };
          
          // 调用更新接口更新一级节点
          updateRoadSectionDistanceTest(firstLevelForm).then(response => {
            // console.log("一级节点平均长度更新成功", firstLevelNode.id);
          }).catch(error => {
            console.error("一级节点平均长度更新失败:", error);
            // this.$modal.msgError("一级节点平均长度更新失败");
          });
        }
      });
    }
  }
}
</script>
